<template>
  <Dialog v-model="dialogVisible" :title="'危害识别'" width="80%">
    <Hazards
      ref="hazardsRef"
      :selected-hazards="currentRowData?.hazards || []"
      :show-checkbox="true"
      @select="handleTempSelect"
      @close-dialog="closeDialog"
      @handle-save="handleSave"
    />
  </Dialog>
</template>

<script lang="ts" setup>
import { computed, nextTick, ref } from 'vue'
import { ElMessage } from 'element-plus'
import Dialog from '@/components/Dialog/src/Dialog.vue'
import Hazards from '@/views/system/hazards/JobSurveyIndex.vue'
import { HazardsApi } from '@/api/system/hazards'

// 定义危害类型接口
interface Hazard {
  id: number
  type: number
  cnName: string
  whgroup?: number
  letter?: string
  sampling?: {
    sampleDays: number
    pointCount: number
    sampleCount: number
    contactHours: number
    startDay: number
    timeType: 'long' | 'short'
    sampleType: 'fix' | 'personal' | 'none'
    isCustomTime?: boolean
    sampleDuration?: number
    flowRate?: number
    strengthType?: number
  }
  personalProtection?: string
  personalProtectionList?: string[]
  personalProtectionIds?: number[]
  protectiveFacilities?: string
  protectiveFacilitiesList?: string[]
  protectiveFacilitiesIds?: number[]
  fluctuationTime?: string
  remark?: string
  workContent?: string
  source?: string
  workLocation?: number
  testStandard?: string
  measuringEquipment?: string
  storageLife?: string
}

// 修改 props 定义
const props = defineProps<{
  row: {
    id: string
    testItem: string
    contactTime: string | undefined
    fluctuationTime: string
    remark: string
    workLocation?: number
    hazards: Hazard[]
    personalProtection: string
    personalProtectionList: string[]
    personalProtectionIds: number[]
    protectiveFacilities: string
    protectiveFacilitiesList: string[]
    protectiveFacilitiesIds: number[]
    sampleMethod: number | undefined
    longShortTime: number | undefined
    sampleDuration: number | undefined
    flowRate: number | undefined
    strengthType: number | undefined
    sampleDays: number | undefined
    sampleCount: number | undefined
    backupCount: number | undefined
    sampleCode: string
    editing?: string
    editingValue?: number | string
    isFirstHazard: boolean
    hazardCount: number
    originalId: string
    sampling?: {
      sampleDays: number
      pointCount: number
      sampleCount: number
      contactHours: number
      startDay: number
      timeType: 'long' | 'short'
      sampleType: 'personal' | 'none'
      isCustomTime?: boolean
      sampleDuration?: number
    }
  } | null
  operationType: number
  positionName?: string // 新增：岗位名称参数
}>()

// 定义组件的emit
const emit = defineEmits(['update', 'close'])

// 组件内部状态
const dialogVisible = ref(false)
const hazardsRef = ref()
const tempSelectedHazards = ref<Hazard[]>([])
const tempRowData = ref<any>(null)

// 计算属性：获取当前行数据
const currentRowData = computed(() => tempRowData.value || props.row)

// 打开弹窗方法
const open = async (rowData?: any) => {
  if (rowData) {
    tempRowData.value = rowData
  }

  if (!currentRowData.value) {
    console.error('没有可用的行数据')
    ElMessage.error('数据错误，请重试')
    return
  }
  dialogVisible.value = true
  await nextTick()
}

// 处理临时选择
const handleTempSelect = async (hazards: Hazard[]) => {
  try {
    // 获取所有危害的详细信息，包括whgroup和三列
    const hazardsWithWhgroup = await Promise.all(
      hazards.map(async (hazard) => {
        try {
          const detail = await HazardsApi.getHazards(hazard.id)
          // console.log(`获取到危害[${hazard.id}]的详细信息:`, JSON.stringify(detail))
          return {
            ...hazard,
            whgroup: detail.whgroup,
            testStandard: detail.testStandard,
            measuringEquipment: detail.measuringEquipment,
            storageLife: detail.storageLife
          }
        } catch (error) {
          console.error(`获取危害[${hazard.id}]详细信息失败:`, error)
          return hazard
        }
      })
    )

    tempSelectedHazards.value = hazardsWithWhgroup
  } catch (error) {
    console.error('获取危害whgroup失败:', error)
    ElMessage.error('获取危害信息失败，请重试')
  }
}

// 计算限值类型默认值
const getDefaultStrengthType = (hazard: any, sampleType: string) => {
  console.log(`[限值类型默认值] 获取限值类型默认值:sampleType`, JSON.stringify(sampleType))
  // 确保类型转换为数字进行比较
  const hazardType = parseInt(hazard.type) || 0
  const hasMac = hazard.mac != null && hazard.mac !== '' && hazard.mac !== '—'
  console.log(`hazardType`, hazardType)
  console.log(`hasMac`, hasMac)
  let defaultValue = 1

  if (sampleType === 'fix') {
    if (hazardType === 1) {
      defaultValue = 7
    } else if (hazardType === 2 && hasMac) {
      defaultValue = 3
    } else {
      defaultValue = 1
    }
  }

  console.log(
    `[限值类型默认值] 危害: ${hazard.cnName}, 原始类型: ${hazard.type}, 转换后类型: ${hazardType}, 采样类型: ${sampleType}, MAC: ${hazard.mac}, 默认限值类型: ${defaultValue}`
  )

  return defaultValue
}

const handleSave = async () => {
  try {
    if (!currentRowData.value) return

    const selectedList = tempSelectedHazards.value

    // 1. 处理清空情况
    if (selectedList.length === 0) {
      emit('update', [])
      closeDialog()
      return
    }

    // 2. 更新新增危害的统计计数
    const existingIds = new Set(currentRowData.value.hazards.map((h: any) => h.id))
    const newHazardIds = selectedList
      .filter(h => !existingIds.has(h.id))
      .map(h => h.id)

    if (newHazardIds.length > 0) {
      HazardsApi.updateCounts(newHazardIds).catch(e => console.warn('更新计数失败', e))
    }

    // 3. 分组逻辑 (按 whgroup 合并)
    const hazardsByGroup = new Map<string | number, Hazard[]>()

    selectedList.forEach(hazard => {
      const typeStr = String(hazard.type)
      const whgroup = hazard.whgroup

      const isChemicalGroup = typeStr === '2' && whgroup !== null && whgroup !== undefined && whgroup !== '' && whgroup !== '—'

      if (isChemicalGroup) {
        if (!hazardsByGroup.has(whgroup!)) {
          hazardsByGroup.set(whgroup!, [])
        }
        hazardsByGroup.get(whgroup!)?.push(hazard)
      } else {
        const uniqueKey = `single_${hazard.id}`
        hazardsByGroup.set(uniqueKey, [hazard])
      }
    })

    // 4. 构建最终数据
    const finalHazards: Hazard[] = []

    const contactTime = parseFloat(String(props.row?.contactTime || 0))
    const sampleType = props.row?.workLocation === 1 ? 'fix' : 'personal'
    const basePositionName = (props.positionName || '').replace(/工$/, '')
    const workContentStr = basePositionName + '工作'

    for (const [key, groupHazards] of hazardsByGroup) {
      const isMergeGroup = groupHazards.length > 1 && !String(key).startsWith('single_')

      // 获取主危害
      const primaryHazard = groupHazards[0]

      // 🟢 修复点：使用 Set 对名称去重
      let finalCnName = primaryHazard.cnName
      if (isMergeGroup) {
        finalCnName = [...new Set(groupHazards.map(h => h.cnName))].join('、')
      }

      const sourceStr = `${basePositionName}时产生${finalCnName}`

      // 检查是否存在于旧数据中（用主危害ID查找）
      const existingItem = currentRowData.value.hazards.find((h: any) => h.id === primaryHazard.id)

      let newHazardItem: Hazard

      if (existingItem) {
        // 保留原有配置
        newHazardItem = {
          ...existingItem,
          cnName: finalCnName, // 更新名称
          operationType: props.operationType,
          workContent: workContentStr,
          source: sourceStr,
        }
      } else {
        // 新增危害，初始化默认值
        const strengthType = getDefaultStrengthType(primaryHazard, sampleType)

        newHazardItem = {
          ...primaryHazard,
          cnName: finalCnName,
          operationType: props.operationType,
          personalProtection: props.row?.personalProtection || '',
          personalProtectionList: [...(props.row?.personalProtectionList || [])],
          personalProtectionIds: [...(props.row?.personalProtectionIds || [])],
          protectiveFacilities: props.row?.protectiveFacilities || '',
          protectiveFacilitiesList: [...(props.row?.protectiveFacilitiesList || [])],
          protectiveFacilitiesIds: [...(props.row?.protectiveFacilitiesIds || [])],
          fluctuationTime: props.row?.fluctuationTime || '',
          remark: props.row?.remark || '',
          workContent: workContentStr,
          source: sourceStr,
          workLocation: props.row?.workLocation,
          sampling: {
            sampleDays: 1,
            pointCount: 1,
            sampleCount: 1,
            contactHours: contactTime,
            startDay: 1,
            timeType: 'long',
            sampleType: sampleType,
            isCustomTime: false,
            sampleDuration: 0,
            flowRate: 10,
            strengthType: strengthType
          }
        }
      }

      finalHazards.push(newHazardItem)
    }
    console.log(`[最终结果] 共处理 ${JSON.stringify(finalHazards)} `)
    emit('update', finalHazards)
    closeDialog()

  } catch (error) {
    console.error('保存危害失败:', error)
    ElMessage.error('保存失败，请重试')
  }
}

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false
  tempSelectedHazards.value = []
  tempRowData.value = null
  emit('close')
}

// 暴露方法给父组件
defineExpose({
  open
})
</script>

<style lang="scss" scoped>
// 可以根据需要添加样式
</style>
